package com.java.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.java.auth.mapper.SysUserMapper;
import com.java.auth.service.IndexService;
import com.java.auth.service.SysMenuService;
import com.java.common.constants.UserConstants;
import com.java.common.utils.JwtHelper;
import com.java.common.utils.MD5Util;
import com.java.common.utils.R;
import com.java.model.system.SysUser;
import com.java.vo.system.LoginVo;
import com.java.vo.system.RouterVo;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysMenuService sysMenuService;
    /**
     * 登录
     *
     * @param loginVo
     * @return
     */
    @Override
    public R login(LoginVo loginVo) {
        //获取用户名和密码
        //根据用户名查询数据库，查询用户信息是否存在
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",loginVo.getUsername());
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if(sysUser==null){
            return R.fail().message("用户不存在！，请注册再进行登录！");
        }
        //存在，检验状态是否为1，再密码校验
        if(sysUser.getStatus().intValue()==0){
            return R.fail().message("用户被禁用！，请联系管理员处理后再进行登录！");
        }
        String password = MD5Util.encode(loginVo.getPassword() + UserConstants.USER_SLAT);
        if(!sysUser.getPassword().equals(password)){
            return R.fail().message("密码错误！，请重新登录登录！");
        }
        //jwt生成token
        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
        //封装token数据
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        return R.ok(map).message("登陆成功！");
    }

    /**
     * 获取用户菜单和按钮
     *
     * @param userId
     * @return
     */
    @Override
    public R info(Long userId) {

        //根据id，获取用户信息
        SysUser sysUser = sysUserMapper.selectById(userId);
        //获取用户菜单
        List<RouterVo> routersList = sysMenuService.findUserMenuByUserId(userId);
        //获取用户操作权限
        List permsList = sysMenuService.findPermsByUserId(userId);

        Map<String,Object> map = new HashMap<>();
        map.put("name",sysUser.getUsername());
        map.put("roles","[admin]");
        map.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("buttons", permsList);
        map.put("routers", routersList);
        System.out.println(routersList);
        return R.ok(map);
    }
}
